
  public class ListNode {
      int val;
    ListNode next;
    ListNode() {}
    ListNode(int val) { this.val = val; }
    ListNode(int val, ListNode next) { this.val = val; this.next = next; }
}

//非递归的
class Solution {
    public ListNode reverseKGroup(ListNode head, int k) {
        if(k == 1){
            return head;
        }

        //1、求链表的长度
        int size = 0;
        ListNode cur = head;
        while(cur != null){
            cur = cur.next;
            size++;
        }
        cur = head;

        //2、反转链表（两个循环）
        int count = size/k;//2
        ListNode newHead = new ListNode(-1);
        ListNode pos = newHead;
        ListNode prev = head;
        for(int i = count;i > 0;i--){
            prev = cur;
            ListNode curPrev = prev;
            cur = prev.next;
            for(int j = k-1; j > 0; j--){
                ListNode curNext = cur.next;
                cur.next = curPrev;
                curPrev = cur;
                cur = curNext;
            }
            pos.next = curPrev;
            pos = prev;
        }
        pos.next = cur;
        return newHead.next;
    }
}